package com.example.audio_test.ui

import android.graphics.SurfaceTexture
import android.hardware.Camera
import android.opengl.GLSurfaceView
import android.opengl.GLSurfaceView.RENDERMODE_WHEN_DIRTY
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.audio_test.R
import com.kun.base.ui.AbsBaseActivity
import kotlinx.android.synthetic.main.activity_gl_surface_view.*
import java.lang.Exception

/**
 *glSurfaceView 预览相机
 *
 * @author : Kun
 * @date : 2021/7/1
 * @time : 17:23
 */
@Route(path = "/recordTest/GlSurfaceViewActivity")
class GlSurfaceViewActivity : AbsBaseActivity(), SurfaceTexture.OnFrameAvailableListener {

    private var cameraStatus = 0

    private var camera: Camera? = null

    private var mRender: MyRender? = null

    private var mSurfaceTexture: SurfaceTexture? = null;

    override fun getLayoutId(): Int {
        return R.layout.activity_gl_surface_view
    }

    override fun initViewModel() {
    }

    override fun initView() {
        gl_surfaceView.setEGLContextClientVersion(2)
        mSurfaceTexture = SurfaceTexture(MyRender.createOesTextureObject())
        mSurfaceTexture!!.setOnFrameAvailableListener(this)

        mRender = MyRender(mSurfaceTexture!!)
        gl_surfaceView.setRenderer(mRender)
        gl_surfaceView.renderMode = RENDERMODE_WHEN_DIRTY

        btn_change_camera.setOnClickListener {
            cameraStatus = cameraStatus xor 1
            if(camera!=null){
                camera!!.startPreview()
                camera!!.release()
            }

            mRender!!.mBoolean=true
            mRender!!.cameraStatus=cameraStatus

            camera = Camera.open(cameraStatus)
            try {
                camera!!.setPreviewTexture(mSurfaceTexture)
            }catch (e:Exception){
                e.printStackTrace()
            }
            camera!!.startPreview()

        }

        camera = Camera.open(cameraStatus)
        try {
            camera!!.setPreviewTexture(mSurfaceTexture)
        }catch (e:Exception){
            e.printStackTrace()
        }
        camera!!.startPreview()
    }

    override fun onFrameAvailable(surfaceTexture: SurfaceTexture?) {
        gl_surfaceView.requestRender()
    }
}